package com.example.software.utils;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

public class QRCodeDecoder {

    public String decodeQRCode(String filePath) throws Exception {
        // 加载图片文件
        BufferedImage image = ImageIO.read(new File(filePath));

        // 创建二值化图像
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        HybridBinarizer binarizer = new HybridBinarizer(source);
        BinaryBitmap bitmap = new BinaryBitmap(binarizer);

        // 创建多格式解码器并解码
        MultiFormatReader multiFormatReader = new MultiFormatReader();
        Result result;
        try {
            result = multiFormatReader.decode(bitmap);
            return result.getText();
        } catch (NotFoundException e) {
            throw new RuntimeException("二维码未找到或无法解码");
        }
    }
}
